#!/bin/bash

# options: make, make afl, make klee
# clean options: clean, clean afl, clean klee

AFL_DIR="afl_build"
KLEE_DIR="klee_build"
COV_DIR="cov_build"


function make_cov {
	echo "make gcov"
	CC=gcc CXX=g++ CFLAGS='-g -fprofile-arcs -ftest-coverage' LDFLAGS="-fprofile-arcs"  ./configure	
	make
}


# Build with afl-gcc (afl)
function make_afl {
	echo "make afl"
	mkdir $AFL_DIR
	cd $AFL_DIR
	CC=afl-clang CXX=afl-clang++ ../configure
	make
	cd ..
}
function clean_afl {
	echo "rm -r $AFL_DIR"
	rm -r $AFL_DIR
}


# Build with wllvm (klee)
function make_klee {
	echo "make klee"	
	mkdir $KLEE_DIR
	cd $KLEE_DIR
	export LLVM_COMPILER=clang	# Export clang as compiler for wllvm
	# -g : Generate source level debug information
	CC=wllvm CXX=wllvm++ CFLAGS=-g ../configure
	make
	
	FILES=$PWD"/*"
	for file in $(find);
	do
		# create bytecode from all executeable file found
		if [[ -x "$file" ]] 
		then
    		echo "try create bytecode from '$file' (because executable)"
    		extract-bc $file
    	fi;
	done
	cd ..
}
function clean_klee {
	echo "rm -r $KLEE_DIR"
	rm -r $KLEE_DIR
}

function clean_all {
	clean_afl
	clean_klee
	clean_cov
 	make clean
 	exit
}

if [[ $# == 1 ]]; then
	echo "try: make, make afl, make klee"
	echo "or:  clean, clean afl, clean klee"
fi;

if [[ $# == 1 ]]; then
	if [[ $1 == "make" ]]; then
		echo "make all"
		make_afl
		make_klee
		exit
	fi;
	if [[ $1 == "clean" ]]; then
		echo "clean all"
		clean_all
		exit
	fi
fi;

if [[ $# == 2 ]]; then	
	if [[ $1 == "make" ]]; then
		if [[ $2 == "afl" ]]; then
			make_afl
		fi;
		if [[ $2 == "klee" ]]; then
			make_klee
		fi;
		if [[ $2 == "cov" ]]; then
			make_cov
		fi;
		exit
	fi;

	if [[ $1 == "clean" ]]; then
		if [[ $2 == "afl" ]]; then
			printf "clean afl: "
			clean_afl
		fi;
		if [[ $2 == "klee" ]]; then
			printf "clean klee: "
			clean_klee
		fi;
		if [[ $2 == "cov" ]]; then
			printf "clean cov: "
			clean_cov
		fi;
		exit
	fi;

fi;
